package com.buaa.airticketbookingsystem.Controller;

import com.buaa.airticketbookingsystem.Entity.User;
import com.buaa.airticketbookingsystem.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
@CrossOrigin
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")

    public Map<String, Object> userLogin(@RequestBody Map<String, String> remap){
        String email = remap.get("email");
        String password = remap.get("password");
        Map<String, Object> map = new HashMap<>();
        try{
            User u = userService.selectUserByEmail(email);
            if(u == null){
                map.put("res", false);
                map.put("message", "该邮箱不存在！");
            }
            else{
                if(u.getIsLogin() == 1){
                    map.put("res", false);
                    map.put("message", "用户已在他处登陆，请退出后重试");
                } else if(password.equals(u.getPassword())){

                    long date = new Date().getTime() / 1000;
                    if(u.getLast_refund() == 0 || u.getLast_refund() + 30 * 24 * 60 * 60 < date){
                        System.out.println(u.getLast_refund());
                        System.out.println(date);
                        userService.highCredit(email);
                        u.setCredit(1);
                    }

                    map.put("res", true);
                    map.put("message", "登陆成功");
                    map.put("user", u);
                }
                else{
                    map.put("res", false);
                    map.put("message", "密码输入错误！");
                }
            }
        }catch(Exception e){
            map.put("res", false);
            map.put("message", "用户登陆失败！");
        }
        return map;
    }
}
